package net.mayee.alice.web.controller.admin.system;

import net.mayee.alice.entity.admin.account.Language;
import net.mayee.alice.web.controller.base.BaseController;
import net.mayee.common.AliceHelper;
import net.mayee.datatables.DtBean;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
public class LanguageController extends BaseController {

    @RequiresPermissions(value = {"language:R"})
    @RequestMapping(value = "/sdm/sys/lag/R")
    public String languageR(Model model) {
        return "system/language/languageR";
    }

    @RequiresPermissions(value = {"language:R"})
    @RequestMapping(value = "/sys/lag/ajax/R")
    public void languageRAjax(HttpServletResponse response, HttpServletRequest request) throws IOException {
        JSONArray array = new JSONArray();
        DtBean dtBean = new DtBean(request);

        int totalRecords = this.getLanguageService().count(new HashMap<String, Object>());
        int totalDisplayRecords = totalRecords;
        if (dtBean.isHasSearch()) {
            totalDisplayRecords = this.getLanguageService().count(dtBean.getSearchParams());
        }
        String defaultLanguage = AliceHelper.getInstance().getJoddProps().getValue("system.default.language");
        List<Language> list = this.getLanguageService().searchByLimit(dtBean.getSearchParams());
        for (int i = 0; i < list.size(); i++) {
            Language lag = list.get(i);
            JSONArray ja = new JSONArray();
            ja.put(lag.getName());
            ja.put(lag.getCode());
            if (lag.getCode().equals(defaultLanguage)) {
                ja.put("<span class=\"label label-success\">" + this.getMessage("net.mayee.alice.web.sys.language.default_language") + "</span>");
            } else {
                ja.put("");
            }
            array.put(ja);
        }

        request.setAttribute("reJSON", dtBean.getJSONString(array, totalRecords, totalDisplayRecords));
    }

}
